<template>
  <div>
    <div class="gva-search-box">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline" @keyup.enter="onSubmit">
        <el-form-item label="任务类型">
          <el-input v-model="searchInfo.jobType" />
        </el-form-item>
        <el-form-item label="同步方式">
          <el-input v-model="searchInfo.syncType" />
        </el-form-item>
        <el-form-item label="任务状态">
          <el-input v-model="searchInfo.state" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        size="small"
        border
        :header-cell-style="{background:'#a3c6d2',color:'#849ba1',padding:'0px'}"
        :cell-style="changeBackRed"
        @selection-change="handleSelectionChange"
      >
        <el-table-column align="left" label="任务编号" prop="odsTbId" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="任务编码" prop="odsTbName" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="任务名称" prop="jobName" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="任务分组" prop="jobGroup" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="任务类型" prop="jobType" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="同步方式" prop="syncType" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="cron表达式" prop="cronExpression" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="调用目标" prop="invokeTarget" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="执行策略" prop="misfirePolicy" :show-overflow-tooltip="true" />
        <el-table-column align="left" label="是否启动" prop="start" :show-overflow-tooltip="true">
          <template #default="scope">{{ getJobStart(scope.row.start) }}</template>
        </el-table-column>
        <el-table-column align="left" label="是否运行" prop="isRunning" :show-overflow-tooltip="true">
          <template #default="scope">{{ getJobRunning(scope.row.odsTbName) }}</template>
        </el-table-column>
        <el-table-column align="left" label="操作" width="160" fixed="right">
          <template #default="scope">
            <el-button type="primary" link icon="edit" class="table-button" @click="updateOdsJobFunc(scope.row)">变更</el-button>
            <el-button v-if="getJobRunning(scope.row.odsTbName)=== '未运行' && scope.row.ready === 1 && scope.row.start === true" type="primary" link icon="CaretRight" class="table-button" @click="clickStartOdsDbJob(scope.row)">开 始</el-button>
            <el-button v-if="getJobRunning(scope.row.odsTbName)=== '运行中'" type="primary" link icon="CircleCloseFilled" class="table-button" @click="clickStopOdsDbJob(scope.row)">停 止</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="dialogJobVisible"
      :before-close="closeDialogJob"
      :title="dialogJobTitle"
      class="dialog-mid"
    >
      <el-form
        ref="elFormJob"
        class="x-form"
        :model="odsJob"
        label-position="right"
        :rules="ruleOdsJob"
        :inline="true"
      >
        <el-form-item label="任务编号:" prop="odsTbId">
          <el-input v-model="odsJob.odsTbId" :disabled="true" />
        </el-form-item>
        <el-form-item label="任务编码:" prop="odsTbName">
          <el-input v-model="odsJob.odsTbName" :disabled="true" />
        </el-form-item>
        <el-form-item label="任务名称:" prop="jobName">
          <el-input v-model="odsJob.jobName" />
        </el-form-item>
        <el-form-item label="任务类型:" prop="jobType">
          <el-select v-model="odsJob.jobType">
            <el-option v-for="item in dictJobType" :key="item.id" :value="item.label" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="同步方式:" prop="syncType">
          <el-select v-model="odsJob.syncType">
            <el-option v-for="item in dictSyncType" :key="item.id" :value="item.label" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="分页同步数量:" prop="pageLimit">
          <el-input v-model="odsJob.pageLimit" />
        </el-form-item>
        <el-form-item label="cron表达式:" prop="cronExpression">
          <el-input v-model="odsJob.cronExpression" />
        </el-form-item>
        <el-form-item label="是否启动:" prop="start">
          <el-switch v-model="odsJob.start" active-color="#13ce66" inactive-color="#ff4949" active-text="是" inactive-text="否" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialogJob">取 消</el-button>
          <el-button type="primary" @click="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import {
  updateOdsJob,
  findOdsJob,
  getOdsJobList,
  getOdsJobRunning,
} from '@/api/odsJob'

import {
  stopOdsDbJob, startOdsDbJob,
} from '@/api/odsDbConfig'
import { ElMessage } from 'element-plus'
import {ref, reactive, onUnmounted} from 'vue'
import { getDict } from '@/utils/dictionary'
import {getAllOdsOdb} from "@/api/odsOdb";

const odsJob = ref({
  odsTbId: 0,
  jobCode: '',
  jobName: '',
  jobGroup: '',
  jobType: 0,
  cronExpression: '',
  invokeTarget: '',
  args: '',
  misfirePolicy: 0,
  concurrent: 0,
  status: 0,
  entryId: 0,
  remarks: '',
})

const ruleOdsJob = reactive({})

const elFormJob = ref()

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})
const jobRunning = ref([])

const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

const onSubmit = () => {
  page.value = 1
  pageSize.value = 10
  getTableData()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const getTableData = async() => {
  const res = await getOdsJobList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (res.code === 0) {
    tableData.value = res.data.list
    total.value = res.data.total
    page.value = res.data.page
    pageSize.value = res.data.pageSize
  }
  const res1 = await getOdsJobRunning()
  if (res1.code === 0) {
    jobRunning.value = res1.data.jobRunning
  }
}

getTableData()

const getJobRunning = (tbName) => {
  if (Object.keys(jobRunning).length > 0) {
    if (tbName in jobRunning.value) {
      if (jobRunning.value[tbName] === 1) {
        return '运行中'
      } else {
        return '未运行'
      }
    } else {
      return '未运行'
    }
  } else {
    return '未运行'
  }
}
const getJobStart = (jobStart) => {
  if (jobStart === true) {
    return '启用'
  } else {
    return '停用'
  }
}

const setOptions = async() => {
}

setOptions()

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const type = ref('')

const updateOdsJobFunc = async(row) => {
  const res = await findOdsJob({ ID: row.ID })
  type.value = 'update'
  dialogJobTitle.value = '修改数据同步任务'
  if (res.code === 0) {
    odsJob.value = res.data.reodsJob
    dialogJobVisible.value = true
  }
}

const dialogJobVisible = ref(false)
const dialogJobTitle = ref()

const closeDialogJob = () => {
  dialogJobVisible.value = false
  odsJob.value = {}
}
const enterDialog = async() => {
  elFormJob.value?.validate(async(valid) => {
    if (!valid) return
    let res
    switch (type.value) {
      case 'update':
        res = await updateOdsJob(odsJob.value)
        break
      default:
        break
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialogJob()
      await getTableData()
    }
  })
}
const dictSyncType = ref([])
const dictJobType = ref([])
const getDictConfig = async() => {
  dictSyncType.value = await getDict('syncType')
  dictJobType.value = await getDict('jobType')
}

const changeBackRed = ({ row, columnIndex }) => {
  if (row.syncType.length < 1 && columnIndex === 4) {
    return { 'background': '#ea8109' }
  } else if (row.jobType.length < 1 && columnIndex === 5) {
    return { 'background': '#ea8109' }
  } else if (row.cronExpression.length < 1 && columnIndex === 6) {
    return { 'background': '#ea8109' }
  } else if (row.start === false && columnIndex === 9) {
    return { 'background': '#ea8109' }
  }
}

const clickStartOdsDbJob = async(data) => {
  const res = await startOdsDbJob(data)
  if (res.code === 0) {
    await getTableData()
    ElMessage({
      type: 'success',
      message: res.msg
    })
  } else {
    ElMessage({
      type: 'warning',
      message: res.msg
    })
  }
}
const clickStopOdsDbJob = async(data) => {
  const res = await stopOdsDbJob(data)
  if (res.code === 0) {
    await getTableData()
    ElMessage({
      type: 'success',
      message: res.msg
    })
  } else {
    ElMessage({
      type: 'warning',
      message: res.msg
    })
  }
}
const getJobRunningList = async() => {
  const res = await getOdsJobRunning()
  if (res.code === 0) {
    jobRunning.value = res.data.jobRunning
  }
}
const init = async() => {
  await getDictConfig()
}
init()

const timer = ref(null)
timer.value = setInterval(() => {
  getJobRunningList()
}, 1000 * 10)

onUnmounted(() => {
  clearInterval(timer.value)
  timer.value = null
})

</script>

<style>
</style>
